from django.views.generic import View
from django.shortcuts import HttpResponse
from django.http.response import JsonResponse
import json
from constant import MessageConstant, StateCode
import re
from .models import User



class UserRegisterCommitValidateApi(View):
    def post(self, request):
        data = json.loads(request.body.decode())

        password = data.get("password", None)
        username = data.get("username", None)
        cpassword = data.get("cpassword", None)
        email = data.get("email", None)
        allow = data.get("allow", None)

        if not all([password, cpassword, username, email, allow]):
            return JsonResponse({"code": StateCode.FAIL, "msg": MessageConstant.DATA_VALIDATE_FAIL})

        if cpassword != password:
            return JsonResponse({"code": StateCode.FAIL, "msg": MessageConstant.PASSWORD_ERROR})

        if allow is None:
            return JsonResponse({"code": StateCode.FAIL, "msg": MessageConstant.NO_ALLOW})

        if re.match(r'\w.@\w.\.\w.', email):
            return JsonResponse({"code": StateCode.FAIL, "msg": MessageConstant.EMAIL_ERROR})

        try:
            user = User.objects.get(username=username)
        except Exception as e:
            user = None

        if user is not None:
            return JsonResponse({"code": StateCode.FAIL, "msg": MessageConstant.USER_HAS})

        try:
            user = User.objects.create(username=username, password=password, email=email, mobile=username)
            user.save()
        except Exception as e:
            return JsonResponse({"code": StateCode.FAIL, "msg": MessageConstant.DB_ERROR})

        return JsonResponse({"code": StateCode.SUCCESS})



class UserLoginCommitValidateView(View):
    def post(self, request):
        data = json.loads(request.body.decode())

        password = data.get("password", None)
        username = data.get("username", None)

        try:
            user = User.objects.get(username=username, password=password)
        except Exception as e:
            return JsonResponse({"code": StateCode.FAIL, "msg": MessageConstant.DATA_VALIDATE_FAIL})

        request.session['user'] = user.to_dict()
        return JsonResponse({"code": StateCode.SUCCESS})


class UserSessionCheckValidateView(View):
    def get(self, request):
        user = request.session['user']
        if user is None:
            return JsonResponse({"code": StateCode.FAIL})
        return JsonResponse({"code": StateCode.SUCCESS, "user": user})



class UserSessionClearValidateView(View):
    def get(self, request):
        request.session.clear()
        return JsonResponse({"code": StateCode.SUCCESS})







